<?php

namespace plugin\admin\app\model\traits;

use plugin\admin\app\model\GoodsActivityRelation;
use support\Request;

trait Relationshipable
{
    protected $relationTable = '';

    protected $relationField = '';

    public function add(Request $request)
    {
        $ids = (array)$request->post('third_party_id', []);
        $id = $request->post('id');

        $relation = (new $this->relationTable)->where($this->relationField, $id)->get()->toArray();
        $goodsIds = array_column($relation, 'goods_id');

        $goodsIds = array_diff($ids, $goodsIds);

        if (count($goodsIds) > 0) {
            $insertData = [];

            foreach ($goodsIds as $goodsId) {
                $insertData[] = [
                    'goods_id' => $goodsId,
                    $this->relationField => $id
                ];
            }

            (new $this->relationTable)->insert($insertData);
        }

        return $this->json(0, '成功');
    }

    public function remove(Request $request)
    {
        $ids = (array)$request->post('third_party_id', []);
        $id = $request->post('id');

        (new $this->relationTable)->where($this->relationField, $id)->whereIn('goods_id', $ids)->delete();

        return $this->json(0, '成功');
    }
}